import 'package:flutter/material.dart';
import 'dart:io';
import 'package:path_provider/path_provider.dart'; // 确保正确导入

void main() {
  runApp(const FileOperationsApp());
}

class FileOperationsApp extends StatelessWidget {
  const FileOperationsApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '文件操作演示',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: const FileOperationsScreen(),
    );
  }
}

class FileOperationsScreen extends StatefulWidget {
  const FileOperationsScreen({super.key});

  @override
  State<FileOperationsScreen> createState() => _FileOperationsScreenState();
}

class _FileOperationsScreenState extends State<FileOperationsScreen> {
  String _fileContent = '';
  String _directoryContent = '';
  String _statusMessage = '';
  bool _isLoading = false;
  final TextEditingController _textController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _textController.text = 'Hello, Dart!\n这是一个测试文件。';
  }

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }

  // 获取文档目录路径
  Future<String> _getDocumentsDirectoryPath() async {
    final directory = await getApplicationDocumentsDirectory(); // 确保方法可用
    return directory.path;
  }

  // 获取文件对象
  Future<File> _getFile() async {
    final path = await _getDocumentsDirectoryPath();
    return File('$path/example.txt');
  }

  // 写入文件
  Future<void> _writeFile() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在写入文件...';
    });

    try {
      final file = await _getFile();
      await file.writeAsString(_textController.text);
      _statusMessage = '文件写入成功';
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('文件写入成功')));
    } catch (e) {
      _statusMessage = '写入失败: $e';
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('写入失败: $e')));
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 读取文件
  Future<void> _readFile() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在读取文件...';
    });

    try {
      final file = await _getFile();
      if (await file.exists()) {
        final content = await file.readAsString();
        setState(() {
          _fileContent = content;
          _statusMessage = '文件读取成功';
        });
      } else {
        _statusMessage = '文件不存在';
        setState(() {
          _fileContent = '文件不存在';
        });
      }
    } catch (e) {
      _statusMessage = '读取失败: $e';
      setState(() {
        _fileContent = '读取失败: $e';
      });
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('读取失败: $e')));
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 列出目录内容
  Future<void> _listDirectory() async {
    setState(() {
      _isLoading = true;
      _statusMessage = '正在列出目录内容...';
    });

    try {
      final directory = await getApplicationDocumentsDirectory(); // 确保方法可用
      final entities = directory.list();

      String result = '';
      await for (final entity in entities) {
        final type = entity is File ? '文件' : '目录';
        result += '$type: ${entity.path}\n';
      }

      setState(() {
        _directoryContent = result.isEmpty ? '目录为空' : result;
        _statusMessage = '目录内容列出成功';
      });
    } catch (e) {
      _statusMessage = '列出失败: $e';
      setState(() {
        _directoryContent = '列出失败: $e';
      });
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('列出失败: $e')));
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('文件操作演示'), centerTitle: true),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 状态显示
            if (_isLoading)
              const LinearProgressIndicator()
            else
              const SizedBox(height: 4),
            Text(
              _statusMessage,
              style: TextStyle(
                color:
                    _statusMessage.contains('成功') ? Colors.green : Colors.red,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),

            // 输入区域
            Card(
              elevation: 4,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '输入要写入的内容:',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    TextField(
                      controller: _textController,
                      maxLines: 5,
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        hintText: '输入文本内容...',
                      ),
                    ),
                    const SizedBox(height: 16),
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _writeFile,
                            child: const Text('写入文件'),
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _readFile,
                            child: const Text('读取文件'),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 文件内容显示
            Card(
              elevation: 4,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '文件内容:',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                        borderRadius: BorderRadius.circular(4),
                        color: Colors.grey.shade50,
                      ),
                      child: SelectableText(
                        _fileContent.isEmpty ? '点击"读取文件"按钮查看内容' : _fileContent,
                        style: const TextStyle(fontFamily: 'monospace'),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 目录内容显示
            Card(
              elevation: 4,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '目录内容:',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    ElevatedButton(
                      onPressed: _listDirectory,
                      child: const Text('列出目录内容'),
                    ),
                    const SizedBox(height: 8),
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey),
                        borderRadius: BorderRadius.circular(4),
                        color: Colors.grey.shade50,
                      ),
                      child: SelectableText(
                        _directoryContent.isEmpty
                            ? '点击"列出目录内容"按钮查看'
                            : _directoryContent,
                        style: const TextStyle(fontFamily: 'monospace'),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 16),

            // 说明文本
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Text(
                '文件操作说明:\n'
                '1. 在文本框中输入内容，点击"写入文件"保存\n'
                '2. 点击"读取文件"查看当前文件内容\n'
                '3. 点击"列出目录内容"查看应用文档目录中的所有文件\n'
                '4. 文件将保存在应用的文档目录中',
                style: TextStyle(fontSize: 14),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
